const path = require('path');
const fse = require('fs-extra');
const ejs = require('ejs');
const mime = require('mime');

module.exports = (config, util) => {

    return async (ctx, next) => {

        // 取根目录
        const rootDir = config.root;
        // 拿到请求url
        const url = ctx.url;
        // 浏览的路径
        const scanPath = path.join(rootDir, url);
        // 读取ejs模版内容
        const dirListPage = fse.readFileSync(path.join(__dirname, './dirList.ejs'), {
            encoding: 'utf-8'
        });
        
        // 确定下路径是否存在
        let isExist = util.isPathExist(scanPath);
        // 拿到文件对象，判断路径是目录还是文件
        let stat = isExist && fse.statSync(scanPath);
        
        if(isExist && stat.isDirectory()) {
            // 读取目录下的文件列表
            const dirList = fse.readdirSync(scanPath);

            // 解析模版
            const content = ejs.render(dirListPage, {
                dirs: dirList,
                root: url === '/' ? '' : url
            });

            // 按照html返回内容
            ctx.type = mime.getType('html');
            ctx.body = content;
        }
        else {
            await next();
        }
    }

}